import NProgress from 'nprogress';
import { debounce, throttle } from '@/utils/utils.js';
import axios from 'axios';
import { genres_3 } from '@/components/common/';
// import { mapGetters, mapMutations } from 'vuex'
import { mapGetters, mapMutations, mapActions } from 'vuex';
export let qukusong = {
    computed: {
        ...mapGetters({
            pageTotal: 'qukuSongPageTotal',
            tableData: 'qukuSongData',
            query: 'qukuSongQuery',
            tagsList: 'tagsList',
            currentSong: 'currentSong',
            currentIndex: 'currentIndex',
            playlist: 'playlist',
            playing: 'playing'
        }),
    },
    destroyed() {
        if (!this.tagsList.some(item => item.name === 'QukuSong')) {
            this.SET_QUKUSONG_DATA([]);
            this.SET_QUKUSONG_PAGETOTAL(0);
            this.SET_QUKUSONG_QUERY({
                show: false,
                checked: false,
                pageIndex: 1,
                pageSize: 10,
                ids: '',
                importName: '',
                actorImportName: '',
                albumImportName: '',
                cppoaName: '',
                genre: '',
                isrc: '',
                status: '',
                creator: '',
                priceType: ''
            });
        } else {}
    },
    data() {
        return {
            playerTitle: '',
            showLyric: true,
            musicAllDuration: 0,
            currentTime: 0,
            isChange: false,
            ulStyleObj: {},
            currentLineNum: 0,
            currentLyric: null,
            playerVisible: false,
            songReady: false,
            genres_3,
            songId: '',
            editVisible: false,
            channelVisible: false,
            channel: null,
            id: null,

            tagList: [],
            form: {
                actorName: [],
                tags: [],
                songName: ''
            }
        }
    },
    watch: {
        $route: {
            deep: true,
            immediate: true,
            handler(a, b) {
                if (a.name === 'QukuSong' && this.query.checked === true) {
                    if (this.tableData.length === 0) {
                        this.getCheckedData();
                    } else {}
                } else if (a.name === 'QukuSong' && this.query.checked === false) {
                    if (this.tableData.length === 0) {
                        this.getData();
                    } else {}
                }
            }
        }

    },
    mounted() {},
    methods: {
        handleClose_2() {
            this.$handleUnlock.call(this, this.close, '/song/unlock', this.songId);
        },
        ...mapMutations({
            SET_QUKUSONG_DATA: 'SET_QUKUSONG_DATA',
            SET_QUKUSONG_PAGETOTAL: 'SET_QUKUSONG_PAGETOTAL',
            SET_QUKUSONG_QUERY: 'SET_QUKUSONG_QUERY',
            setPlayingState: 'SET_PLAYING_STATE',
            setPlayList: 'SET_PLAYLIST',
            setCurrentIndex: 'SET_CURRENT_INDEX',
            SET_QUKUSONG_FORM: 'SET_QUKUSONG_FORM'
        }),
        cellStyle({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 12) {
                return 'white-space: nowrap !important;';
            } else {
                return '';
            }
        },
        handlechange(value) {},
        cancelQuest() {
            if (typeof this.source === 'function') {
                this.source('终止请求');
            }
        },

        async getCheckedData() {
            try {
                let _this = this;
                this.cancelQuest();
                NProgress.start();
                let url = '/song/list';
                let { data: res } = await this.$http[0].get(url, {
                    headers: {},
                    cancelToken: new axios.CancelToken(function executor(c) {
                        _this.source = c;
                    }),
                    params: this.$removeField({
                        page: this.query.pageIndex,
                        size: this.query.pageSize,
                        ids: this.query.ids.trim(),
                        importName: this.query.importName.trim(),
                        actorImportName: this.query.actorImportName.trim(),
                        albumImportName: this.query.albumImportName.trim(),
                        cppoaName: this.query.cppoaName.trim(),
                        genre: this.query.genre,
                        isrc: this.query.isrc,
                        status: this.query.status,
                        creator: this.query.creator,
                        auditFlag: -1
                    })
                });
                if (res.code != '0000') {
                    throw new Error(res.message);
                }
                if (res.data.content && res.data.content.length > 0) {
                    res.data.content.map(item => {
                        item.paused = true;
                        if (item.actors && item.actors.length != 0) {
                            item.actors.name = '';
                            item.actors.map(val => {
                                item.actors.name += val.name + '/';
                            });
                            item.actors.name = item.actors.name.slice(0, -1);
                        } else {
                            item.actors = [];
                            item.actors.name = '';
                        }
                        item.createTime = this.$dateFormat(item.createTime, '', '-');
                        item.updateTime = this.$dateFormat(item.updateTime, '', '-');
                    });
                    this.SET_QUKUSONG_DATA(res.data.content);
                    this.SET_QUKUSONG_PAGETOTAL(res.data.totalElements);

                    var tempQuery = {...this.query };
                    this.$set(tempQuery, 'show', true);
                    this.SET_QUKUSONG_QUERY(tempQuery);
                } else {
                    this.SET_QUKUSONG_DATA([]);
                    this.SET_QUKUSONG_PAGETOTAL(0);
                    var tempQuery = {...this.query };
                    this.$set(tempQuery, 'show', true);
                    this.SET_QUKUSONG_QUERY(tempQuery);
                }

                NProgress.done();
            } catch (err) {
                NProgress.done();
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        handlePush(index, row) {
            this.channelVisible = true;
            this.id = row.id;
        },
        savePush: throttle(function() {
            this.push()
        }, 500),
        async push() {
            try {
                if (
                    this.$isEmpty({
                        channel: this.channel
                    })
                ) {
                    return this.$message.error({
                        duration: 1500,
                        message: '请选择渠道'
                    });
                }
                let url = '/song/publish';
                let { data: res } = await this.$http[0].get(url, {
                    headers: {
                        name: localStorage.getItem('ms_username')
                    },
                    params: this.$removeField({
                        id: this.id,
                        channel: this.channel
                    })
                });
                if (res.code != '0000') {
                    throw new Error(res.message);
                }
                this.$message.success({
                    message: res.message,
                    duration: 1500
                });
                this.channelVisible = false;
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        handleChecked(index, row) {
            this.$router.replace({
                path: '/song/checked',
                query: {
                    id: row.id
                }
            });

            localStorage.setItem('id_song', row.id);
        },
        handleStatusChange: debounce(function(value) {
            setTimeout(() => {
                if (value == true) {
                    this.$set(this.query, 'pageIndex', 1);
                    this.getCheckedData();
                } else {
                    this.$set(this.query, 'pageIndex', 1);
                    this.getData();
                }
            }, 500);
        }, 1000),
        handleEdit(index, row, n) {
            if (n == 1) {
                // 编辑
                this.$handleLock.call(this, index, row, this.edit, '/song/lock', row.id);
                this.$storage.set('operate', {...this.$storage.get('operate'), name1: 'edit' })
            } else {
                // 查看
                this.edit(index, row)
                this.$storage.set('operate', {...this.$storage.get('operate'), name1: 'search' })
            }

        },
        edit(index, row) {
            this.SET_QUKUSONG_FORM({})
            this.$router.replace({
                path: '/song/info',
                query: {
                    id: row.id
                }
            });
            localStorage.setItem('id_song', row.id);
            localStorage.removeItem('indexFlag_song');
        },

        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.SET_QUKUSONG_QUERY(this.query);
            if (this.query.checked == true) {
                this.getCheckedData();
            } else {
                this.tableData.map(v => {
                    v.paused = true;
                });
                this.SET_QUKUSONG_DATA([...this.tableData]);
                this.setPlayingState(false);
                this.setCurrentIndex(-1);
                this.getData();
            }
        },
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.SET_QUKUSONG_QUERY(this.query);
            if (this.query.checked == true) {
                this.getCheckedData();
            } else {
                this.tableData.map(v => {
                    v.paused = true;
                });
                this.SET_QUKUSONG_DATA([...this.tableData]);
                this.setPlayingState(false);
                this.setCurrentIndex(-1);
                this.getData();
            }
        },
        timeFormat(interval) {
            interval = interval | 0; // 相当于Math.floor() 向下取整数
            let minute = (interval / 60) | 0; // 相当于Math.floor() 向下取整数 取分钟
            let second = this._pad(interval % 60); // 取秒
            return `${minute}:${second}`;
        },
        _pad(num, n = 2) {
            let len = num.toString().length;
            while (len < n) {
                num = '0' + num;
                len++;
            }
            return num;
        },
        formatData(array) {
            for (let item of array) {
                item.value = item.id;
                item.label = item.description;
                item.children = [];

                delete item.type;
                delete item.createTime;
                delete item.description;
                delete item.groupId;
                delete item.id;
                delete item.name;
                delete item.status;
                delete item.updateTime;
                delete item.pid;

                if (item.tblTags && item.tblTags.length != 0) {
                    item.children = item.tblTags;

                    delete item.tblTags;
                    this.formatData(item.children);
                } else {
                    delete item.children;
                }
            }
            return array;
        },
        // setValueNull() {
        //     // if (this.query.checked === true) {
        //     //     this.getCheckedData();
        //     // } else {
        //     //     this.getData();
        //     // }
        // },


        close() {
            this.editVisible = false;
        },

        saveTagging: throttle(function() {
            this.save();
        }, 500),
        async save() {
            try {
                let url = '/song/taging';
                let { data: res } = await this.$http[0].get(url, {
                    params: this.$removeField({
                        objectId: this.songId,
                        tagIds: this.form.tags.join(',')
                    }),
                    headers: {
                        name: localStorage.getItem('ms_username')
                    }
                });

                this.$message.success({
                    message: res.message,
                    duration: 1500
                });
                this.form = {
                    actorName: [],
                    tags: [],
                    songName: ''
                };
                this.editVisible = false;
                this.getData();
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        getOneArray(twoArray) {
            var tempArr = [];
            if (twoArray && twoArray.length && twoArray.length > 0) {
                twoArray = Array.from(twoArray);
                twoArray.map(arr => {
                    arr = arr || [];
                    arr = Array.from(arr);
                    tempArr.push(arr[arr.length - 1]);
                });
            }
            return [...new Set(tempArr)];
        },
        async getTagData() {
            try {
                let url = '/tag/tagAll';
                let { data: res } = await this.$http[2].get(url, {
                    params: {
                        type: 1
                    }
                });
                if (res.code != '0000') {
                    throw new Error(res.message);
                }

                if (res.data && res.data.length && res.data.length != 0) {
                    res.data.map(v => {
                        v.disabled = true;
                    });
                    var ret = this.formatData(res.data);

                    this.tagList = ret;
                } else {
                    this.tagList = [];
                }
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        async getEditData(songId) {
            try {
                let url = '/song/getSongTag';
                let { data: res } = await this.$http[0].get(url, {
                    params: this.$removeField({
                        songId
                    })
                });
                if (res.code != '0000') {
                    throw new Error(res.message);
                }
                let { actorName, tags, songName } = res.data;
                actorName = actorName.join(',') || [];
                tags = tags || [];
                this.form = {
                    actorName,
                    tags,
                    songName
                };

                if (res.data.tags && res.data.tags.length && res.data.tags.length > 0) {
                    this.form.tags = res.data.tags;
                } else {
                    this.form.tags = [];
                }
            } catch (err) {
                console.dir(err);
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
        tagging(index, row) {
            this.songId = row.id;
            this.editVisible = true;
            this.tagList = [];
            this.form = {};
            this.getEditData(row.id);
            this.getTagData();
        },

        // handleSelectionChange(val) {
        //     console.log(val)
        //  },
        handleTagging(index, row) {
            this.$handleLock.call(this, index, row, this.tagging, '/song/lock', row.id);
        },

        handleSearch: debounce(function() {
            this.$set(this.query, 'pageIndex', 1);
            if (this.query.checked === true) {
                this.getCheckedData();
            } else {
                this.getData();
            }
        }, 300),
        pause(e) {
            console.log(e)
        },
        async getData() {
            try {
                let _this = this;
                this.cancelQuest();
                NProgress.start();
                this.disabled = true
                let url = '/song/list';
                let { data: res } = await this.$http[0].get(url, {
                    cancelToken: new axios.CancelToken(function executor(c) {
                        _this.source = c;
                    }),
                    params: this.$removeField({
                        page: this.query.pageIndex,
                        size: this.query.pageSize,
                        ids: this.query.ids.trim(),
                        importName: this.query.importName.trim(),
                        actorImportName: this.query.actorImportName.trim(),
                        albumImportName: this.query.albumImportName.trim(),
                        cppoaName: this.query.cppoaName.trim(),
                        genre: this.query.genre,
                        isrc: this.query.isrc,
                        status: this.query.status,
                        creator: this.query.creator,
                        priceType: this.query.priceType,
                        mediaType: 'audio'
                    })
                });

                if (res.code != '0000') {
                    throw new Error(res.message);
                }
                this.aOption = []
                if (res.data.content && res.data.content.length > 0) {

                    res.data.content.map(item => {
                        this.aOption.push({
                            type: 'application/x-mpegURL', //媒体类型，m3u8请给application/x-mpegURL或者application/vnd.apple.mpegURL，其他的会默认为普通音视频，注：微信不支持m3u8
                            src: item.m3u8Path, //音频地址
                            preload: true, //是否预下载，默认为true
                            autoplay: false, //是否自动播放（兼容性不太好），默认为false
                            isLoop: false, //是否循环，默认不循环
                            // controls: 'progress,current,durration' //显示的控件,没有配置controls项则全部显示。
                        })
                        item.paused = true;
                        // if (item.tblSongfiles && item.tblSongfiles.length > 0) {
                        //     item.tblSongfiles[0].filePath = `${process.env.VUE_APP_SRC1}/api/stream/audio?path=${item.tblSongfiles[0].filePath}`;
                        // } else {
                        //     item.tblSongfiles = [
                        //         {
                        //             filePath: ''
                        //         }
                        //     ];
                        // }
                        if (item.actors && item.actors.length != 0) {
                            item.actors.name = '';
                            item.actors.map(val => {
                                item.actors.name += val.name + '/';
                            });
                            item.actors.name = item.actors.name.slice(0, -1);
                        } else {
                            item.actors = [];
                            item.actors.name = '';
                        }


                        if (item.tblSongAuthTerritories && item.tblSongAuthTerritories.length > 0) {
                            item.tblSongAuthTerritories.priceType = ''
                            item.tblSongAuthTerritories.map(v => {
                                if (v.priceType + '' != 'undefined') {
                                    item.tblSongAuthTerritories.priceType += v.priceType + '/'
                                }

                            })
                            item.tblSongAuthTerritories.priceType = item.tblSongAuthTerritories.priceType.slice(0, -1)

                        } else {
                            item.tblSongAuthTerritories = [];
                            item.tblSongAuthTerritories.priceType = ''
                        }

                        item.createTime = this.$dateFormat(item.createTime, '', '-');
                        item.updateTime = this.$dateFormat(item.updateTime, '', '-');
                    });
                    this.SET_QUKUSONG_DATA(res.data.content);
                    this.SET_QUKUSONG_PAGETOTAL(res.data.totalElements);
                    var tempQuery = {...this.query };
                    this.$set(tempQuery, 'show', false);
                    this.SET_QUKUSONG_QUERY(tempQuery);
                    this.setPlayList(res.data.content);
                } else {
                    this.SET_QUKUSONG_DATA([]);
                    this.SET_QUKUSONG_PAGETOTAL(0);
                    var tempQuery = {...this.query };
                    this.$set(tempQuery, 'show', false);
                    this.SET_QUKUSONG_QUERY(tempQuery);
                    this.setPlayList([]);
                }

                NProgress.done();
                this.disabled = false
            } catch (err) {
                this.SET_QUKUSONG_DATA([]);
                this.SET_QUKUSONG_PAGETOTAL(0);
                var tempQuery = {...this.query };
                this.$set(tempQuery, 'show', false);
                this.SET_QUKUSONG_QUERY(tempQuery);
                this.setPlayList([]);
                console.dir(err);
                NProgress.done();
                this.disabled = false
                this.$message.error({
                    message: err.message,
                    duration: 1500
                });
            }
        },
    }
}